<?php
namespace app\index\controller;
use think\Controller;
use think\Log;
class Index extends Controller {
    
     public  static  $appid ='wx103006e3d7513abf';
     public   static  $secret ='0174dfeb3b217227ef59c775db523185';
   
    public function index(){
        //获得参数 signature nonce token timestamp echostr
        $nonce     = $_GET['nonce'];
        $token     = '20e4513ca09d38508e136013b6c0eb4b';
        $timestamp = $_GET['timestamp'];
        //$echostr   = $_GET['echostr'];
        $echostr   = '';
        $signature = $_GET['signature'];
        //形成数组，然后按字典序排序
        $array = array();
        $array = array($nonce, $timestamp, $token);
        sort($array);
        //拼接.成字符串,sha1加密 ，然后与signature进行校验
        $str = sha1( implode( $array ) );
        if( $str  == $signature && $echostr ){
            //第一次接入weixin api接口的时候
            echo  $echostr;
            exit;
        }else{
            $this->reponseMsg();
        }
    }

    public function  show(){
        
    }
    
    public function sign(){
        $param =input('param.');
        $openid = $param['openid'];
        $mobile= '15678288841';
        //插入数据库成功  报名成功
        //$this->a($openid);
    }
    public function add(){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".self::$appid."&secret=".self::$secret;
        $json_token=$this->http_request($url);
        $temp =json_decode($json_token,true);
        $access_token=$temp['access_token'];
        //https://api.weixin.qq.com/customservice/kfaccount/add?access_token=ACCESS_TOKEN
         $data = [
             "touser"=>"OPENID",
              "msgtype"=>"text",
              "text"=>[
                  "content"=>"Hello World"
                  ]
             ];           
                    
        $json_template=json_encode($data);
        //echo $json_template;
        //echo $this->access_token;
        $url = 'https://api.weixin.qq.com/customservice/kfaccount/add?access_token='.$access_token;
        //$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
        $res=$this->http_request($url,urldecode($json_template));
        echo '--------';
        echo $res;
    }
    
    
    public function a($openid){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".self::$appid."&secret=".self::$secret;
        $json_token=$this->http_request($url);
        $temp =json_decode($json_token,true);
        $access_token=$temp['access_token'];
        
        //获得access_token
        //$this->access_token=$access_token[access_token];
        //echo $this->access_token;exit;
        //模板消息
/*        $template=array(
                'touser'=>$openid,
                'template_id'=>"模板代码",
                'url'=>"链接地址",
                'topcolor'=>"#7B68EE",
                'data'=>array(
                        'first'=>array('value'=>urlencode("您好,您有新的订单"),'color'=>"#FF0000"),
                        'keyword1'=>array('value'=>urlencode(date("Y-m-d H:i:s")),'color'=>'#FF0000'),
                        'keyword2'=>array('value'=>urlencode('这是测试'),'color'=>'#FF0000'),
                        'keyword3'=>array('value'=>urlencode('这是测试'),'color'=>'#FF0000'),
                        'keyword4'=>array('value'=>urlencode('这是测试'),'color'=>'#FF0000'),
                        'remark'=>array('value'=>urlencode('这是测试'),'color'=>'#FF0000'), )
                    );*/
         $data = [
             "touser"=>$openid,
              "msgtype"=>"text",
              "text"=>[
                  "content"=>"Hello World"
                  ]
             ];           
                    
        $json_template=json_encode($data);
        //echo $json_template;
        //echo $this->access_token;
        $url = 'https://api.weixin.qq.com/customservice/kfaccount/add?access_token='.$access_token;
        //$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
        $res=$this->http_request($url,urldecode($json_template));
        echo '--------';
        echo $res;
        //if ($res[errcode]==0) echo '发送成功';    
    }
    
    function http_request($url,$data=array()){
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            // POST数据
            curl_setopt($ch, CURLOPT_POST, 1);
            // 把post的变量加上
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            $output = curl_exec($ch);
            curl_close($ch);
            return $output;
    }

    public function reponseMsg(){
        //1.获取到微信推送过来post数据（xml格式）
        //$postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
        $postArr = file_get_contents("php://input"); 
        //2.处理消息类型，并设置回复类型和内容
        /*<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[FromUser]]></FromUserName>
<CreateTime>123456789</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[subscribe]]></Event>
</xml>*/
        $postObj = simplexml_load_string( $postArr );
        //$postObj->ToUserName = '';
        //$postObj->FromUserName = '';
        //$postObj->CreateTime = '';
        //$postObj->MsgType = '';
        //$postObj->Event = '';
        Log::record('警告'.$postArr,'notice');
        //判断该数据包是否是订阅的事件推送
        if( strtolower( $postObj->MsgType) == 'event'){
            //如果是关注 subscribe 事件
            if( strtolower($postObj->Event == 'subscribe') ){
                //回复用户消息(纯文本格式)
                $toUser   = $postObj->FromUserName;
                $fromUser = $postObj->ToUserName;
                $time     = time();
                $msgType  =  'news';
                $content  = '欢迎关注我们的微信公众账号'.$postObj->FromUserName;
                $template ="<xml>
                  <ToUserName><![CDATA[%s]]></ToUserName>
                  <FromUserName><![CDATA[%s]]></FromUserName>
                  <CreateTime>%s</CreateTime>
                  <MsgType><![CDATA[%s]]></MsgType>
                  <ArticleCount>%s</ArticleCount>
                  <Articles>
                    <item>
                      <Title><![CDATA[%s]]></Title>
                      <Description><![CDATA[%s]]></Description>
                      <PicUrl><![CDATA[%s]]></PicUrl>
                      <Url><![CDATA[%s]]></Url>
                    </item>
                  </Articles>
                </xml>";
                $articleCount ='1';
                $title = '点击报名参与willspace活动';
                $description ='willspace是中国最大的房产公司';
                $picurl = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1587048198054&di=4faf6cabffc4c0a8725bd7eef42beb9d&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F017d8d5a7342e8a80120a12327632e.png%401280w_1l_2o_100sh.png';
                $url = 'http://willspace.shuokepro.com/index/index/sign?openid='.$toUser;
             /*  $template = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            </xml>";*/
                $info     = sprintf($template, $toUser, $fromUser, $time, $msgType, $articleCount,$title,$description,$picurl,$url);
                echo $info;
                /*<xml>
                <ToUserName><![CDATA[toUser]]></ToUserName>
                <FromUserName><![CDATA[fromUser]]></FromUserName>
                <CreateTime>12345678</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA[你好]]></Content>
                </xml>*/
            }
        }
}}